using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using QueryBuilder.Controls.Configuration;

namespace QueryBuilder.Controls
{
    /// <summary>
    /// 
    /// </summary>
    public class ExpressionFactory : ITemplateSectionVisitor
    {
        private DataField comparisionDataField;
        private ComparisonTemplateConfiguration comparisonTemplateConfiguration;
        private int currentIndex;
        private List<DataField> dataFields;
        private StackPanel stackPanel;
        private ItemsControl containerElement;

        public ExpressionFactory(ComparisonTemplateConfiguration comparisonTemplateConfiguration)
        {
            this.comparisonTemplateConfiguration = comparisonTemplateConfiguration;
        }

        public void Visit(Comparison comparison)
        {
            this.stackPanel.Children.Add(this.comparisionDataField);
        }

        public void Visit(Variable variable)
        {
            DataField dataField = this.dataFields[this.currentIndex];
            this.stackPanel.Children.Add(dataField);
            this.currentIndex++;
            
        }

        protected virtual ItemsControl ContainerElement
        {
            get
            {
                if (this.containerElement == null)
                {
                    this.containerElement = new ItemsControl();
                }
                return this.containerElement;
            }
        }

        public FrameworkElement GetVisualizer(DataField dataField)
        {
            return dataField; 
        }

        public FrameworkElement GetVisualizer(DataField comparisonDataField, List<DataField> dataFields, string comparisonName)
        {
            this.stackPanel = new StackPanel()
            {
                Orientation = Orientation.Horizontal
            };
            if (dataFields.Count > 0)
            {
                this.currentIndex = 0;
                this.dataFields = dataFields;
                this.comparisionDataField = comparisonDataField;
                IEnumerable<TemplateSection> templateSections = this.comparisonTemplateConfiguration.GetComparisonTemplate(comparisonName);

                foreach (TemplateSection templateSection in templateSections)
                {
                    templateSection.Accept(this);
                }
            }
            return stackPanel;
        }
    }
}